import subprocess
import socket


def network_basics():
    # 1. Ping测试
    try:
        result = subprocess.run(['ping', '-n', '4', '192.168.1.1'],
                                capture_output=True, text=True)
        print("Ping结果:", "成功" if result.returncode == 0 else "失败")
    except:
        print("Ping测试失败")

    # 2. 端口扫描基础
    def check_port(ip, port):
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
                sock.settimeout(2)
                result = sock.connect_ex((ip, port))
                return result == 0
        except:
            return False

    # 测试常见PLC端口
    ports_to_check = {
        102: 'Siemens S7',
        502: 'Modbus TCP',
        44818: 'Allen-Bradley'
    }

    test_ip = '127.0.0.1'
    for port, description in ports_to_check.items():
        status = "开放" if check_port(test_ip, port) else "关闭"
        print(f"端口 {port}({description}): {status}")


network_basics()
